import type { FormItemRule } from 'element-plus'
// 数据不能为空
export const isNoEmpty = {
  required: true,
  validator: (rule, value, callback) => {
    if ((!value && value !== 0) || (value && value.length === 0)) {
      console.log(rule)
      return callback(new Error('该项不能为空'))
    }
    return callback()
  },
  trigger: ['blur', 'change']
}

// 是否是正整数
export const isPositiveInteger = {
  required: true,
  validator: (rule, value, callback) => {
    if (!value && value !== 0) {
      return callback(new Error('该项不能为空'))
    }
    if (typeof value !== 'number') {
      return callback(new Error('请输入数字'))
    }
    if (!/^[1-9]\d*$/.test(String(value))) {
      console.log(rule)
      return callback(new Error('请输入大于0的正整数'))
    }
    return callback()
  },
  trigger: ['blur', 'change']
}
// 是否是身份证号格式

export const isIdCardNumber = {
  required: true,
  validator: (rule, value, callback) => {
    if (!value && value !== 0) {
      return callback(new Error('该项不能为空'))
    }
    if (typeof value !== 'string') {
      return callback(new Error('请输入字符串'))
    }
    const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (!reg.test(value)) {
      console.log(rule)
      return callback(new Error('证件号码不正确'))
    }
    return callback()
  },
  trigger: ['blur', 'change']
}
// 是否是手机号
export const isPhoneNumber = {
  required: true,
  validator: (rule, value, callback) => {
    if (!value && value !== 0) {
      return callback(new Error('该项不能为空'))
    }
    if (typeof value !== 'string') {
      return callback(new Error('请输入字符串'))
    }
    const reg = /^1[3456789]\d{9}$/
    if (!reg.test(value)) {
      console.log(rule)
      return callback(new Error('手机号码不正确'))
    }
    return callback()
  },
  trigger: ['blur', 'change']
}
// 将rules规则的对象数据转为string类型
export const stringifyRules = (rulesItem: FormItemRule): string => {
  return JSON.stringify(rulesItem, function (key, val) {
    if (typeof val === 'function' && key === 'validator') {
      return val + ''
    }
    return val
  })
}
// 将string类型的规则转为rules对象
export const parseRules = (rulesItemJson: string): FormItemRule => {
  const params = JSON.parse(rulesItemJson)
  console.log(params, '=s=s=s==s=s=')
  for (let key of Object.keys(params)) {
    if (key === 'validator') {
      params[key] = eval(params[key])
    }
  }
  return params
}
export const defaultRuleStr =
  "{\n    required: true,\n    validator: (rule,value,callback) => {\n        if(!value && value !== 0) {\n            return callback(new Error('该项不能为空'))\n        }\n        // 校验代码编写处\n        \n        return callback()\n    },\n    trigger:['blur', 'change']\n}"
